package com.czk.run;

import com.czk.utils.FileUtil;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;

import static org.objectweb.asm.Opcodes.*;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/7/21 16:15
 */
public class GenerateInterfaceWithField {
    public static void main(String[] args) {
        String filePath = "F:\\IdeaProjects\\asm\\target\\classes\\com\\czk\\sample\\FiledInterface.class";
        byte[] bytes = generate();
        FileUtil.writeBytes(filePath, bytes);
    }

    private static byte[] generate() {
        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
        // 访问类
        cw.visit(V1_8, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE,
                "com/czk/sample/FiledInterface",
                null,
                "java/lang/Object",
                null);
        {
            FieldVisitor fieldVisitor = cw.visitField(ACC_PUBLIC | ACC_FINAL | ACC_STATIC,
                    "intValue",
                    "I",
                    null,
                    10);
            fieldVisitor.visitEnd();
        }
        {
            FieldVisitor fieldVisitor = cw.visitField(ACC_PUBLIC + ACC_FINAL + ACC_STATIC, // 访问标识
                    "s", // 字段名称
                    "Ljava/lang/String;", // 字段类型
                    null, // 方法描述符
                    "czk"); // 字段值
            fieldVisitor.visitEnd();
        }
        {
            // 生成注解
            cw.visitAnnotation("com/czk/anotation/Czk", false);
            cw.visitEnd();
        }
        cw.visitEnd();
        return cw.toByteArray();
    }
}
